<?php
/*
Plugin Name: ArchivePress
Plugin URI: http://code.google.com/p/archivepress/
Description: Archiving blogs with blogs.
Version: 1.0.0
Author: University of London Computer Centre
Author URI: http://code.google.com/p/archivepress/
License: GPL2
*/
	ini_set("display_errors","0");
// constants
	define('ARCHIVEPRESS','archivepress');
	// Pre-2.6 compatibility
	if ( ! defined( 'WP_PLUGIN_DIR' ) )
		define( 'WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins' );
	// ArchivePress plugin directory	
	define( 'WP_ARCHIVEPRESS_DIR', WP_PLUGIN_DIR . '/archivepress' );
	// ArchivePress Prefix
	define( 'WP_ARCHIVEPRESS_PREFIX', 'arpr_' );
	
// configuration & dependencies
	// Internationalization 
	load_plugin_textdomain( ARCHIVEPRESS, WP_ARCHIVEPRESS_DIR );
		
	require_once(WP_ARCHIVEPRESS_DIR . '/archivepress.conf.php' );
	global $ArchivePress;

// cron functions
	// web and unix cron
	add_action('init', 'arpr_unix_or_web_fetch');
	function arpr_unix_or_web_fetch() {
		require_once(WP_ARCHIVEPRESS_DIR . '/archivepress.cron.php');
	}
	// wpcron
	add_action('plugins_loaded', 'arpr_wp_fetch');
	function arpr_wp_fetch() {
		global $ArchivePressLog;
		global $ArchivePress;
		// esecute script
		$ArchivePressLog->logIt(ArchivePressLog::LOG_BASIC,__("Cron job started successfully.",ARCHIVEPRESS));
		
		// get active feeds 
		$activeFeeds = array();
		$activeFeeds = $ArchivePress->getFeeds(true,false);
		foreach($activeFeeds as $feed){
			// check if I have to fetch the feed
			if( (time() - strtotime($feed["last_update"])) >= (int)$feed["interval"] ) {
				$ArchivePressLog->logIt(ArchivePressLog::LOG_BASIC,sprintf(__("Fetching feed %s (%s)> posts added: %d ",ARCHIVEPRESS),$feed["name"],$feed["url"],$ArchivePress->fetchFeed($feed)));
			}
		}
	}
	
// Activate, Deactivate, Update and Remove Hooks
	function arpr_activate() {
		// wpcron ON
		wp_schedule_event(time()-8000, 'hourly', 'plugins_loaded');
		
		require(ABSPATH . 'wp-content/plugins/archivepress/archivepress.conf.php');
		$ArchivePress->Activate();
	}
	register_activation_hook( __FILE__, 'arpr_activate' );	
	function arpr_deactivate() {
		// wpcron OFF
		wp_clear_scheduled_hook('archivepress_wp_cron');
		
		require(ABSPATH . 'wp-content/plugins/archivepress/archivepress.conf.php');
		$ArchivePress->Deactivate();
	}
	register_deactivation_hook( __FILE__, 'arpr_deactivate' );
	function arpr_remove() {
		// wpcron OFF
		wp_clear_scheduled_hook('archivepress_wp_cron');
		
		require(ABSPATH . 'wp-content/plugins/archivepress/archivepress.conf.php');
		$ArchivePress->Remove();
	}	
	register_uninstall_hook(__FILE__, 'arpr_remove');

	
	
// WordPress Admin Area Pages
	add_action('admin_menu', WP_ARCHIVEPRESS_PREFIX . 'add_pages');
	function arpr_add_pages() {
	    // New Top Level Menu
	    add_menu_page('ArchivePress', 'ArchivePress', 'administrator', WP_ARCHIVEPRESS_DIR . '/archivepress.php', WP_ARCHIVEPRESS_PREFIX . 'toplevel_page');
	    // Submenus
	    //add_submenu_page('ArchivePress', 'Basic Options', 'Basic Options', 'administrator', 'sub-page', 'mt_sublevel_page');
	
	}	
	function arpr_toplevel_page(){
		// globals
		global $ArchivePress;
		global $ArchivePressLog;
	
		// DISPLAY FEEDS
		// GET ACTIVE FEEDS
		$activeFeeds = array();
		$activeFeeds = $ArchivePress->getFeeds(false,false);
		echo "<form action='' enctype='multipart/form-data' method='post'>
				<input type='hidden' value='yes' name='update' />
				<table cellpadding='5' cellspacing='10'>
				<tr style='font-weight:bold;'><td>Feed Name</td><td>Feed Original url</td><td>Last Update</td><td>Manual update</td></tr>";
		foreach($activeFeeds as $feed){
			if($feed["is_comment"] == "no"){
				if($feed["is_new"] == "no"){
					echo "<tr><td>".$feed["name"]."</td><td>".$feed["url"]."</td><td>".$feed["last_update"]."</td><td><input type='submit' value='Update' name='update_".$feed["id"]."' /> <input type='submit' value='Update Comments' name='updatecomments_".$feed["id"]."' /></td></tr>";
				}else{
					echo "<tr><td>".$feed["name"]."</td><td>".$feed["url"]."</td><td>".$feed["last_update"]."</td><td><input type='submit' value='Update' name='update_".$feed["id"]."' /> <input type='submit' value='Update Comments' name='updatecomments_".$feed["id"]."' /><br /><input type='file' name='xml_".$feed["id"]."' /><input type='submit' value='Upload Blog' name='uploadblog_".$feed["id"]."' /></td></tr>";
				}	
			}
		}
		echo "</table></form>";
		// UPDATE FEEDS MANUALLY
		if(isset($_POST["update"])) {
			foreach($activeFeeds as $feed){
				if(isset($_POST['update_'.$feed["id"]])) {
					$ArchivePressLog->logIt(ArchivePressLog::LOG_BASIC,sprintf(__("Fetching feed %s (%s)> posts added: %d ",ARCHIVEPRESS),$feed["name"],$feed["url"],$ArchivePress->fetchFeed($feed)));
				}
				if(isset($_POST['updatecomments_'.$feed["id"]])) {
					// eventually fetch comments
					$ArchivePressLog->logIt(ArchivePressLog::LOG_BASIC,sprintf(__("Fetching feed %s (%s)> posts added: %d ",ARCHIVEPRESS),$feed["name"],$feed["url"],$ArchivePress->fetchFeedComments($feed["id"])));
				}
				if(isset($_POST['uploadblog_'.$feed["id"]])) {
					// 1. check if is a "text" file
					if($_FILES['xml_'.$feed["id"]]['type'] == "text/xml"){
						// 2. check if is a feed format (RSS or ATOM)
						$content = utf8_encode(file_get_contents($_FILES['xml_'.$feed["id"]]['tmp_name']));
						try {
							if($ArchivePress->isFeed("",$content)){
								// PARSE IT!
								// temp values
								$feed["file"]		= $content;
								$feed["protocol"]	= $ArchivePress->lastFeedCheckedProt;
								$ArchivePress->fetchFeed($feed);
							}
						}catch (Exception $e){
							echo $e->getMessage();
						}
						
					} else {
						echo "DISPLAY ERROR: file type not supported!";
					}
					
					
					
				}
			}
		}
		
		echo "<br /><br /><br />";
		
		
		// ADD feeds
		echo "<form action='' method='post'>
				<table cellpadding='5' cellspacing='10'>
				<tr><td>Feed Name</td><td><input type='text' value='Feed Name' name='name' /></td></tr>
				<tr><td>Feed or website url</td><td><input type='text' value='http://' name='url' /></td></tr>
				<tr><td colspan='2'><input type='submit' value='Add Feed' name='add' /></td></tr>
				";
	
		echo "</table></form>";
		if(isset($_POST["add"])) {
			// these are texts!
			//$testURL = "http://digitalcuration.blogspot.com/";
			//$testURL = "http://digitalcuration.blogspot.com/feeds/posts/default";
			//$testURL = "http://digitalcuration.blogspot.com/feeds/posts/default?alt=rss";
			//$testURL = "http://wesleyanargus.com/2010/02/19/%E2%80%9Cdr-horrible%E2%80%9D-a-terrifyingly-successful-campus-production/";
			//$testNAME = "Digital Curation";
			$testURL = $_POST["url"];
			$testNAME = $_POST["name"];
			
			$feedAdded = false;
			$lastSentence = "";
			// ADD NEW FEED PROCEDURE
			// check if is a feed url
			try {
				if($ArchivePress->isFeed($testURL)){
					try {
						$ArchivePress->addLastCheckedFeed($testNAME,true);
						$feedAdded = true;
						$lastSentence = "DISPLAY SUCCESS: feed successfully added";
					} catch (Exception $e) {
						$lastSentence = $e->getMessage();
						$feedAdded = false;
					}
				} else {
					// try autodiscovery
					$feeds = array();
					try {
						$feeds = FeedAutoDiscovery::getFeedLinks($testURL);
						// If the feed was not already added
						if($ArchivePress->isFeedNew($feeds)) {
							// Add Feed
							try {
								$ArchivePress->addFeed($feeds,$testURL,$testNAME);
								$feedAdded = true;
								$lastSentence = "DISPLAY SUCCESS: feed successfully added";
							} catch (Exception $e) {
								$lastSentence = $e->getMessage();
								$feedAdded = false;
							}
						} else {
							$lastSentence = "DISPLAY ERROR: feed already added!";
						}
					} catch (Exception $e) {
						$lastSentence = $e->getMessage();
						$feedAdded = false;
					}
				}
			} catch (Exception $e) {
				// page not found or other curl errors
				$lastSentence = $e->getMessage();
				$feedAdded = false;
			}
			echo $lastSentence."<br><br><br>";
			
	
		}
		echo "<br /><br /><br />";
						
		
	}
	
	
// DASHBOARD WIDGET(S)
	// Create the function to output the contents of our Dashboard Widget
	function archivepress_dashboard_widget_function() {
		global $wp_registered_sidebars,$ArchivePress;
		
		// get blogs
		$blogs = $ArchivePress->getBlogs();
		$totBlogs = $blogs["total"];
		$activeBlogs = $blogs["active"];
		
		// get fetched posts
		$posts = $ArchivePress->getPosts();
		
		// get fetched comments
		$comments = $ArchivePress->getComments();
		
		// get authors
		$authors = $ArchivePress->getAuthors();
		
		// get last blog fetched
		$lastFetched = $ArchivePress->getLastFetched("blog");
		$lastBlog = $lastFetched["blog"];
		$lastTime = $lastFetched["datetime"];
		
		// get next blog to fetch
		$nextToFetch = $ArchivePress->getNextToFetch("blog");
		$nextBlog = $nextToFetch["blog"];
		$nextTime = $nextToFetch["datetime"];
		
		// get last comment fetched
		$lastFetched = $ArchivePress->getLastFetched("comment");
		$lastComment = $lastFetched["blog"];
		if(strlen($lastComment) > 28)
			$lastComment = substr($lastComment,0,25)."...";
		$lastCTime = $lastFetched["datetime"];
		
		// get next comment to fetch
		$nextToFetch = $ArchivePress->getNextToFetch("comment");
		$nextComment = $nextToFetch["blog"];
		if(strlen($nextComment) > 28)
			$nextComment = substr($nextComment,0,25)."...";
		$nextCTime = $nextToFetch["datetime"];		
		
		// SHOW THEM
		echo'<p class="sub">'.__("At a Glance",ARCHIVEPRESS).'</p>
			<div class="table">
				<table>
				<tbody>
					<tr class="first">
						<td class="first b"><a href="">'.$totBlogs.'</a></td>
						<td class="t posts"><a href="">'.__("Blogs",ARCHIVEPRESS).'</a> <a class="active">('.$activeBlogs.' '.__("active",ARCHIVEPRESS).')</a></td>
					</tr>
					<tr>
						<td class="first b"><a href="">'.$posts.'</a></td>
						<td class="t pages"><a href="">'.__("Posts added",ARCHIVEPRESS).'</a></td>
					</tr>

					<tr>
						<td class="first b"><a href="">'.$comments.'</a></td>
						<td class="t cats"><a href="">'.__("Comments added",ARCHIVEPRESS).'</a></td>
					</tr>
					<tr>
						<td class="first b"><a href="">'.$authors.'</a></td>
						<td class="t tags"><a href="">'.__("Authors added",ARCHIVEPRESS).'</a></td>
					</tr>
				</tbody>
				</table>
			</div>
			<div class="versions">
			<br />
			<p class="sub">'.__("Blog: ",ARCHIVEPRESS).'</p>
				<p>'.__("Last fetched: ",ARCHIVEPRESS).'<span class="b">'.$lastBlog.'</span> <span class="b">(<a>'.mysql2date('F jS, Y @ H:i',$lastTime).'</a>)</span></p>
				<p>'.__("Next fetched: ",ARCHIVEPRESS).'<span class="b">'.$nextBlog.'</span> <span class="b">(<a>'.date('F jS, Y @ H:i',$nextTime).'</a>)</span></p>
			<br />
			<p class="sub">'.__("Comments: ",ARCHIVEPRESS).'</p>
				<p>'.__("Last fetched: ",ARCHIVEPRESS).'<span class="b">'.$lastComment.'</span> <span class="b">(<a>'.mysql2date('F jS, Y @ H:i',$lastCTime).'</a>)</span></p>
				<p>'.__("Last fetched: ",ARCHIVEPRESS).'<span class="b">'.$nextComment.'</span> <span class="b">(<a>'.date('F jS, Y @ H:i',$nextCTime).'</a>)</span></p>
				<br class="clear">
			</div>
		';
	} 

	// Create the function use in the action hook
	function archivepress_add_dashboard_widgets() {
		wp_add_dashboard_widget('archivepress_dashboard_widget', 'ArchivePress Right Now', 'archivepress_dashboard_widget_function');	
	} 
	
	// Hook into the 'wp_dashboard_setup' action to register our other functions
	add_action('wp_dashboard_setup', 'archivepress_add_dashboard_widgets' );
	
	// add widgets css
	function archivepress_custom_style() {
		echo '	<style type="text/css">
					#archivepress_dashboard_widget p.sub,#archivepress_dashboard_widget .table,#archivepress_dashboard_widget .versions{
						margin:-12px;
					}
					#archivepress_dashboard_widget .inside{
						font-size:12px;
					}
					#archivepress_dashboard_widget p.sub{
						font-style:italic;
						font-family:Georgia,"Times New Roman","Bitstream Charter",Times,serif;
						padding:5px 10px 15px;
						color:#777;
						font-size:13px;
					}
					#archivepress_dashboard_widget .table{
						background:#f9f9f9;
						border-top:#ececec 1px solid;
						border-bottom:#ececec 1px solid;
						margin:0 -9px 10px;
						padding:0 10px;
					}
					#archivepress_dashboard_widget table{
						width:100%;
					}
					#archivepress_dashboard_widget table td{
						border-top:#ececec 1px solid;
						padding:3px 0;
						white-space:nowrap;
					}
					#archivepress_dashboard_widget table tr.first td{
						border-top:none;
					}
					#archivepress_dashboard_widget td.b{
						padding-right:6px;
						text-align:right;
						font-family:Georgia,"Times New Roman","Bitstream Charter",Times,serif;
						font-size:14px;
					}
					#archivepress_dashboard_widget td.b a{
						font-size:18px;
					}
					#archivepress_dashboard_widget td.b a:hover{
						color:#d54e21;
					}
					#archivepress_dashboard_widget .t{
						font-size:12px;
						padding-right:12px;
						padding-top:6px;
						color:#777;
					}
					#archivepress_dashboard_widget .t a{
						white-space:nowrap;
					}
					#archivepress_dashboard_widget td.first,#archivepress_dashboard_widget td.last{
						width:1%;
					}
					#archivepress_dashboard_widget .active{
						color:green;
					}
					#archivepress_dashboard_widget .versions{
						padding:6px 10px 12px;
					}
					#archivepress_dashboard_widget .versions .b{
						font-weight:bold;
					}
					#archivepress_dashboard_widget a.button{
						float:right;
						clear:right;
						position:relative;
						top:-5px;
					}
				</style>';
	}
	add_action('admin_head', 'archivepress_custom_style');
	
		
	
// Template tags definition	
	
	// get special page links
	function arpr_getpage($page) {
		return get_page_link((int)get_option(WP_ARCHIVEPRESS_PREFIX.$page));
	}
	// original post link
	function arpr_get_ori_link($post_id){
		return get_post_meta($post_id, WP_ARCHIVEPRESS_PREFIX."original_url",true);
	}
	// post fetch date
	function arpr_get_fetch_date($post_id){
		return get_post_meta($post_id, WP_ARCHIVEPRESS_PREFIX."fetch_date",true);
	}	
	// original blog link
	function arpr_get_blog_link($cat_id){
		// globals
		global $ArchivePress;
		return $ArchivePress->get_blog_link((int)$cat_id);
	}	
?>